package com.mengdie.shuidi.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.blankj.utilcode.utils.AppUtils;
import com.blankj.utilcode.utils.FileUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.mengdie.shuidi.AppConfig;
import com.mengdie.shuidi.AppContext;
import com.mengdie.shuidi.AppUpdate;
import com.mengdie.shuidi.OkHeader;
import com.mengdie.shuidi.R;
import com.mengdie.shuidi.api.HttpUrls;
import com.mengdie.shuidi.event.UpdateEvent;
import com.mengdie.shuidi.helper.UIHelper;
import com.mengdie.shuidi.manager.MDAccountMgr;
import com.mengdie.shuidi.manager.MDUserMgr;
import com.mengdie.shuidi.manager.RobustVersionManager;
import com.mengdie.shuidi.manager.URLManager;
import com.mengdie.shuidi.model.AppEntity;
import com.mengdie.shuidi.model.BaseModel;
import com.mengdie.shuidi.model.ExceedUserEnetity;
import com.mengdie.shuidi.model.SessionEnetity;
import com.mengdie.shuidi.model.UserEnetity;
import com.mengdie.shuidi.ui.interfaces.CheckUrlInterface;
import com.mengdie.shuidi.ui.interfaces.CheckUrlPresent;
import com.mengdie.shuidi.ui.interfaces.LoginInterface;
import com.mengdie.shuidi.ui.interfaces.LoginPresent;
import com.mengdie.shuidi.utils.MDUtil;
import com.mengdie.shuidi.utils.StringToAscii;
import com.mengdie.shuidi.utils.ToastUtil;
import com.orhanobut.logger.Logger;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;


public class SplashActivity extends AppCompatActivity implements CheckUrlInterface {
    private static String BASE_URL = null;
    private final static int TIME_OUT = 1000;
    private Handler handler = new Handler();
    private Runnable runnable;
    private AppUpdate mAppUpdate;
    private CheckUrlPresent mCheckUrlPresent;
    private List<String> mStringList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        EventBus.getDefault().register(this);
        requestPermission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE);

        mAppUpdate = new AppUpdate(SplashActivity.this, false);
        mCheckUrlPresent = new CheckUrlPresent(this);


        //系统的版本
        int localCode = AppUtils.getAppVersionCode(this);
        String localName = AppUtils.getAppVersionName(this);

        int relCode = RobustVersionManager.getInstance().getRelCode();
//        String relName = RobustVersionManager.getInstance().getRelName();

        //如果 app 版本大于本地保存的真实版本(版本更新或者第一次安装),更新本地真实虚拟版本
        if (localCode > relCode) {
            saveVersion(localCode, localName, localName);
            RobustVersionManager.getInstance().clearRobustCode();//清除本地存储的补丁版本号
            //判断清除之前补丁
            if (FileUtils.isFileExists(Environment.getExternalStorageDirectory().getPath() + File.separator + "robust")) {
//                Logger.e("文件存在");
                FileUtils.deleteDir(Environment.getExternalStorageDirectory().getPath() + File.separator + "robust");
            }

        }

        if (FileUtils.isFileExists(Environment.getExternalStorageDirectory().getPath() + File.separator + "robust" + "/patch.jar")) {
            Logger.e("patch.jar" + "true");
            UIHelper.loadPatch(false, 0, "");
        }

        //补丁版本
        int vCode = RobustVersionManager.getInstance().getvCode();
        String vName = RobustVersionManager.getInstance().getvName();

        TextView versionText = (TextView) findViewById(R.id.version_text);
        versionText.setText("版本号 v" + vName + "." + vCode);


    }

    private void saveVersion(int localCode, String localName, String relName) {
        RobustVersionManager.getInstance().setRelCode(localCode);
        RobustVersionManager.getInstance().setRelName(localName);
        // RobustVersionManager.getInstance().setvCode(relCode);
        RobustVersionManager.getInstance().setvName(relName);
        RobustVersionManager.getInstance().saveVersion();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        //根据 Tag 取消请求
        OkGo.getInstance().cancelTag(this);

    }

    /**
     * Request permissions.
     */
    private void requestPermission(String... permissions) {
        AndPermission.with(this)
                .runtime()
                .permission(permissions)
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {
                        getBaseUrl(HttpUrls.IMG_URL1);
                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(@NonNull List<String> permissions) {
                        requestPermission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE);
                    }
                })
                .start();
    }


    //获取 baseurl
    private void getBaseUrl(final String imgUrl) {
        OkGo.get(imgUrl + "?t=" + String.valueOf(System.currentTimeMillis()))//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        if (imgUrl.contains("shanghai")) {
                            // showDialog();//
                            //两次请求域名都失败,直接进入登录判断
                            startLoginStep();
                            return;
                        }
                        getBaseUrl(HttpUrls.IMG_URL2);
                    }

                    @Override
                    public void onSuccess(String str, Call call, Response response) {
                        decodeAndInit(str);
                    }
                });
    }


    /**
     * 解密   初始化
     *
     * @param str
     */
    private void decodeAndInit(String str) {
        String subStr = str.substring(str.indexOf("5B2D3E"), str.indexOf("3C2D5D"));
        String substrFinal = subStr.substring(6);
        String ascill = StringToAscii.convertHexToString(substrFinal);
        String baseUri = MDUtil.mdDecrypt(ascill);//异或解密
        String[] urlList = baseUri.split("\\|");
        mStringList = Arrays.asList(urlList);
        URLManager.setBaseUrlList(mStringList);
        mCheckUrlPresent.check();
    }

    //从图片中  请求的某一个域名可以用,回调此方法
    @Override
    public void onSuccess() {
//        mAppUpdate.checkUpdate();
        getAppConfig();
    }

    private int size = 1;

    @Override
    public void onError() {
        if (size != mStringList.size()) {
            URLManager.updateBaseUrl(size);
            mCheckUrlPresent.check();
            size++;
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("友情提示").setMessage("线路升级中,请稍后重试")
                    .setNegativeButton("重试", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            getBaseUrl(HttpUrls.IMG_URL1);
                        }
                    }).setPositiveButton("退出", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    System.exit(0);
                }
            });
            builder.create().show();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(UpdateEvent event) {
        startLoginStep();
    }

    /**
     * 开始登陆,1000毫秒之后完成登陆的第一个条件
     */
    private void startLoginStep() {

        runnable = new Runnable() {
            @Override
            public void run() {
//                if (AppConfig.getInstance().getHasLauch()) {
                if (MDAccountMgr.getInstance().isPassowrd()) {
                    new LoginPresent(new LoginInterface() {
                        @Override
                        public void onSuccess(String response) {
                            loginSuccDeal(response);
                        }

                        @Override
                        public void onError() {
                            ToastUtil.showToast("网络请求失败");
                            Intent splash = new Intent(SplashActivity.this, LoginActivity.class);
                            startActivity(splash);
                            finish();
                        }
                    }, SplashActivity.this).login(MDAccountMgr.getInstance().getLoginName(), MDAccountMgr.getInstance().getLoginPwd());
                } else {
                    Intent splash = new Intent(SplashActivity.this, LoginActivity.class);
                    startActivity(splash);
                    finish();
                }
//                } else {
//                    Intent splash = new Intent(SplashActivity.this, LeadActivity.class);
//                    startActivity(splash);
//                    finish();
//                }

            }
        };
        handler.postDelayed(runnable, TIME_OUT);
    }

    /**
     * 成功登录 处理
     *
     * @param s
     */
    private void loginSuccDeal(String s) {
        Gson gson = new Gson();
        BaseModel baseModels = new Gson().fromJson(s, BaseModel.class);
        if (baseModels.getRet().equals("0")) {
            Type userType = new TypeToken<BaseModel<SessionEnetity>>() {
            }.getType();
            BaseModel<SessionEnetity> baseModel;
            try {
                baseModel = gson.fromJson(s, userType);
            } catch (JsonSyntaxException e) {
                baseModel = gson.fromJson(s, BaseModel.class);
            }
            SessionEnetity sessionInfo = baseModel.getData();
            MDAccountMgr.getInstance().setSessionId(sessionInfo.getSession());
            MDAccountMgr.getInstance().writeToCache(AppContext.getInstance());
            UserEnetity user = sessionInfo.getUserInfo();
            MDUserMgr.getInstance().setAvatar(user.getAvatar());
            MDUserMgr.getInstance().setId(user.getId());
            MDUserMgr.getInstance().setUsername(user.getUsername());
            MDUserMgr.getInstance().setShowUsername(user.getShowUsername());
            MDUserMgr.getInstance().setAwardFlag(user.getAward_flag());
            MDUserMgr.getInstance().setNickname(user.getNick_name());
            MDUserMgr.getInstance().setChange(user.getChange());
            MDUserMgr.getInstance().setEmail(user.getEmail());
            MDUserMgr.getInstance().setNum(user.getNum() + "");
            MDUserMgr.getInstance().setPhone(user.getPhone());
            MDUserMgr.getInstance().setMoney(Double.valueOf(user.getMoney()));
            MDUserMgr.getInstance().setStatus(user.getStatus());
            MDUserMgr.getInstance().setTime(user.getExpire_time_format());
            MDUserMgr.getInstance().setLastTime(user.getLast_time());
            MDUserMgr.getInstance().setLastTimeType(user.getLast_time_type());
            MDUserMgr.getInstance().setToken(user.getToken());
            MDUserMgr.getInstance().setLogin(true);

            Intent login = new Intent(SplashActivity.this, MainActivity.class);
            startActivity(login);
            finish();
        } else if (baseModels.getRet().equals("1")) {
            Type exceed = new TypeToken<BaseModel<List<ExceedUserEnetity>>>() {
            }.getType();
            BaseModel<List<ExceedUserEnetity>> exceeModel;
            try {
                exceeModel = gson.fromJson(s, exceed);
            } catch (JsonSyntaxException e) {
                exceeModel = gson.fromJson(s, BaseModel.class);
            }
            if (exceeModel.getCode().equals("overtop")) {

                List<ExceedUserEnetity> list = exceeModel.getData();
                UIHelper.showTerminal(SplashActivity.this, list, UIHelper.SPLASH_DIALOG, "1");
            } else {
                ToastUtil.showToast(baseModels.getMsg());
                Intent splash = new Intent(SplashActivity.this, LoginActivity.class);
                startActivity(splash);
                finish();
            }
        } else {
            ToastUtil.showToast(baseModels.getMsg());
            Intent splash = new Intent(SplashActivity.this, LoginActivity.class);
            startActivity(splash);
            finish();
        }
    }


    /**
     * 获取初始化信息
     */
    public void getAppConfig() {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHead(this))
                .post(AppContext.getInstance().getBaseUrl() + "account/get_url")
                .tag(this)
                .execute(new StringCallback() {

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
//                        URLManager.updateBaseUrl();
//                        getAppConfig();
                        ToastUtil.showToast("初始化信息失败");
//                        startLoginStep();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        Type appType = new TypeToken<BaseModel<AppEntity>>() {
                        }.getType();

                        BaseModel<AppEntity> baseModel;

                        try {
                            baseModel = gson.fromJson(s, appType);
                        } catch (Exception e) {
                            baseModel = gson.fromJson(s, BaseModel.class);
                        }

                        if (baseModel.getRet().equals("0")) {
                            Logger.e(baseModel.getData().toString());
                            AppConfig.getInstance().saveAppCofig(baseModel.getData());
                            startLoginStep();
                        } else {
                            ToastUtil.showToast(baseModel.getMsg());
                        }
                    }
                });
    }


    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.drawable.app_logo)
                .setMessage("网络请求失败,请重试")
                .setNegativeButton("重试", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        getBaseUrl(HttpUrls.IMG_URL1);
                    }
                }).setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                System.exit(0);
            }
        }).create().show();
    }


}
